package com.leesche.zcsp.node.app.v1.controller.register;

import com.leesche.zcsp.node.app.v1.constants.AppContants;
import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.pay.wecha.data.Message;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.gernerator.MobileCodeGernerator;
import com.leesche.zcsp.node.utils.web.gernerator.TimeGreaterUilt;
import com.leesche.zcsp.node.utils.web.gernerator.TokenGernerator;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.model.SysUser;
import com.leesche.zcsp.node.web.model.SysUserCriteria;
import com.leesche.zcsp.node.web.model.SysUserToken;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysModuleCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysUserDto;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.app.version1.controller.register
 * @Description:( 在这里描述这个类是做什么的 )
 * @date 2016年11月14日 16:05
 */
@Controller
@RequestMapping(value = "/app/v1/register")
public class AppRegisterController extends UserTemplate {

    private static final Logger logger = Logger
            .getLogger(AppRegisterController.class);

    @Autowired
    private SmsService smsService;

    /**
     * @param username     用户名
     * @param moblienumber 手机号（可为空）
     * @param password     登录密码（已经过加密的密文）
     * @return 注册结果
     * @Title: addWechatUserInfo(@RequestParam String username, @RequestParam String moblienumber, @RequestParam String password)
     * @Description: TODO(APP->用户注册)
     * @author Jerry Chan
     * @date 2016/11/26 18:11
     */
    @ResponseBody
    @RequestMapping(value = "submitUserInfo", method = RequestMethod.POST)
    public Map<String, Object> addWechatUserInfo(String factoryCode, String smsCode, String username, String moblienumber, String password) {
        try {
            if (factoryCode == null || "".equals(factoryCode)) {
                return WebResult.failure("工厂码不能为空").toMap();
            }

            if (username == null || "".equals(username)) {
                return WebResult.failure("用户名不能为空").toMap();
            } else {
                SysUser user = new SysUser();
                user.setUsername(username);
                user = sysUserService.findUserByUsername(user);
                if (user != null) {
                    return WebResult.failure("用户名已存在").toMap();
                }

                user = new SysUser();
                user.setMobile(moblienumber);
                user = sysUserService.findUserByUsername(user);
                if (user != null) {
                    return WebResult.failure("手机号码已存在").toMap();
                }

            }

            if (password == null || "".equals(password)) {
                return WebResult.failure("密码不能为空").toMap();
            }

            Map<String, Object> result = validSMSCode(smsCode);
            if (result != null) return result;

            VaildPhone validPhone = PhoneCodeCacheTimer.get(smsCode);
            if (!moblienumber.equals(validPhone.getPhone())) {
                return WebResult.failure("与获取短信的手机号码一致").toMap();
            }

            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setBusinessno(factoryCode);
            condition.setNtype(2);
            List<SysUserDto> userDto = sysUserService.findListsByCondition(condition);
            if(userDto == null || userDto.size() <= 0){
                return WebResult.failure("工厂码不存在，请核对后再输入").put("ERROR", "smscode").toMap();
            }else{
                //短信验证通过后，清除短信验证码
                PhoneCodeCacheTimer.remove(smsCode);
            }

            SysUser sysUser = new SysUser();
            // 所有商户的父级ID都是超级管理员
            sysUser.setPuserid(userDto.get(0).getUserid());
            sysUser.setAdminid(1L);

            sysUser.setUsername(username);
            sysUser.setMobile(moblienumber);
            sysUser.setPassword(QEncodeUtil.md5Encrypt(password));
            // 所有商户的类型都是4
            sysUser.setNtype(4);
            // 所有商户的备注都是“商业用户”
            sysUser.setRemark("商业用户");
            // 所有商户的状态默认都是在用
            sysUser.setState(1);
            // 所有商户只要手机验证码通过，手机验证都是已验证
            sysUser.setMobileconfirmed(1);
            sysUser.setCreatetime(new Date());
            // 所有商户的有效期默认都是3年
            sysUser.setOuttime(TimeGreaterUilt.specifiedTime(Calendar.YEAR, 3));

            sysUser = sysUserService.addUserInfo(sysUser);
            if (sysUser != null) {
                //保存用户登录状态
                SysUserToken userToken = new SysUserToken();
                TokenGernerator.setupUserToken(userToken, sysUser.getUserid());
                sysUserTokenService.insertSelective(userToken);

                Integer loginType = Constants.MODULE_TYPE_APP;
                QuerySysModuleCondition querySysModuleCondition = new QuerySysModuleCondition();
                querySysModuleCondition.setnType(loginType);
                querySysModuleCondition.setUserId(sysUser.getUserid());
                List<Long> userModules = sysModuleService.findModuleIDbyUserID(querySysModuleCondition);
                sysUserService.saveLoginState(sysUser, userModules, loginType, userToken.getToken());

                return WebResult.success().put("data", userToken.getToken()).toMap();
            }
            return WebResult.failure("注册失败，请稍后重试").toMap();
        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: validUser(String mobilenumber, String username)
     * @Description: TODO(验证用户名和手机号是否存在)
     * @author Jerry Chan
     * @date 2016/12/1 19:23
     */
    @ResponseBody
    @RequestMapping(value = "validregister", method = RequestMethod.POST)
    public Map<String, Object> validUser(String mobilenumber, String username,String factoryCode) {

        try {

            if (mobilenumber == null || "".equals(mobilenumber)) {
                return WebResult.failure("手机号码不能为空").toMap();
            }

            if (username == null || "".equals(username)) {
                return WebResult.failure("用户名不能为空").toMap();
            }

            if (factoryCode == null || "".equals(factoryCode)) {
                return WebResult.failure("工厂码不能为空").toMap();
            }

            SysUser user = new SysUser();
            user.setUsername(username);
            user = sysUserService.findUserByUsername(user);
            if (user != null) {
                return WebResult.failure("用户名已存在").toMap();
            }

            user = new SysUser();
            user.setMobile(mobilenumber);
            user = sysUserService.findUserByUsername(user);
            if (user != null) {
                return WebResult.failure("手机号码已存在").toMap();
            }


            QuerySysUserCondition condition = new QuerySysUserCondition();
            condition.setBusinessno(factoryCode);
            condition.setNtype(2);
            List<SysUserDto> userDto = sysUserService.findListsByCondition(condition);
            if(userDto == null || userDto.size() <= 0){
                return WebResult.failure("工厂码错误，请核对").toMap();
            }

            return this.beginSendMsg(mobilenumber);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: validUser(String mobilenumber, String username)
     * @Description: TODO(验证短信验证码)
     * @author Jerry Chan
     * @date 2016/12/1 19:23
     */
    @ResponseBody
    @RequestMapping(value = "validPhoneCode", method = RequestMethod.POST)
    public Map<String, Object> validPhoneCode(String smsCode) {

        try {
            Map<String, Object> result = validSMSCode(smsCode);
            if (result != null) return result;

            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @return 返回null表示校验通过
     * @Title: validSMSCode(String smsCode)
     * @Description: TODO(校验短信验证码)
     * @author Jerry Chan
     * @date 2016/12/8 16:01
     */
    private Map<String, Object> validSMSCode(String smsCode) {

        if (smsCode == null || "".equals(smsCode)) {
            return WebResult.failure("短信验证码不能为空").toMap();
        }

        VaildPhone validPhone = PhoneCodeCacheTimer.get(smsCode);
        if (validPhone != null) {
            if (validPhone.getValidTime() < new Date().getTime()) {
                PhoneCodeCacheTimer.remove(smsCode);
                return WebResult.failure("短信验证码已过期，请重新获取").toMap();
            }
            return null;
        } else {
            return WebResult.failure("短信验证码错误，请重新输入").toMap();
        }
    }


    /**
     * @param mobileNum 手机号码
     * @return 发送短信结果
     * @Title: beginSendMsg(String mobileNum, HttpSession session)
     * @Description: TODO(开始发送短信)
     * @author Jerry
     * @date 2016-10-29 10:35:55
     */
    private Map<String, Object> beginSendMsg(String mobileNum) throws Exception {
        //生成随机码
        String mobileCode = MobileCodeGernerator.mobileCodeGernerator();
        //发送短信
        Message<String> smsReport = smsService.sendSMS(mobileNum, mobileCode);
        //存在到session 发送成功
        if (Message.isSuccess(smsReport.getType())) {
            //有效时间
            long validTime = new Date().getTime() + (Constants.NOTIC_DEFAULT_MOBLIE_CODE_MAXINACTIVEINTERVAL * 60000);
            //保存短信验证码
            VaildPhone validPhone = new VaildPhone(validTime, mobileNum);
            PhoneCodeCacheTimer.put(mobileCode, validPhone);

            return WebResult.success().info(Constants.getMobileCodeVaildMsg(mobileNum)).toMap();
        } else {
            String errMag = smsReport.getContent();
            if ("InvalidRecNum.Malformed".equals(errMag)) {
                return WebResult.failure("手机号不正确,请输入正确的手机号码").toMap();
            } else if ("InvalidSendSms".equals(errMag)) {
                return WebResult.failure("获取短信过于频繁,请稍后重试").toMap();
            } else {
                return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
            }
        }
    }


}
